package com.example.esp8266;

import android.content.SharedPreferences;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import org.eclipse.paho.client.mqttv3.MqttCallback;

public class MainViewModel extends ViewModel {

    public final MutableLiveData<MqttParamsWrapper> paramsWrapper = new MutableLiveData<>(null);
    private MqttConnectUtil mqttConnectUtil;


    public void initMqttUtil(MqttParamsWrapper wrapper){
        if (wrapper.isEmpty()) return;
        if (mqttConnectUtil != null && mqttConnectUtil.isConnected()) mqttConnectUtil.disconnect();
        mqttConnectUtil = new MqttConnectUtil(wrapper);
    }

    public void putMqttParam(SharedPreferences sp, MqttParamsWrapper wrapper) {
       sp.edit().putString("productKey", wrapper.getProductKey())
                .putString("deviceName", wrapper.getDeviceName())
                .putString("deviceSecret", wrapper.getDeviceSecret())
                .putString("pubTopic", wrapper.getPub_topic())
                .putString("subTopic", wrapper.getSub_topic())
                .apply();
        paramsWrapper.setValue(wrapper);
    }

    public void loadLocalMqttParams(SharedPreferences sp){
        MqttParamsWrapper mqttParamsWrapper = new MqttParamsWrapper(
                sp.getString("productKey", ""),
                sp.getString("deviceName", ""),
                sp.getString("deviceSecret", ""),
                sp.getString("pubTopic", ""),
                sp.getString("subTopic", "")
        );
        paramsWrapper.setValue(mqttParamsWrapper);
    }


    public void startConnect(){
        if (mqttConnectUtil == null) return;
        if (mqttConnectUtil.isConnected()) mqttConnectUtil.disconnect();
        mqttConnectUtil.connect();
    }

    public void sendMsg(String msg){
        if (mqttConnectUtil == null) return;
        mqttConnectUtil.publishMessage(msg);
    }

    public void setCallback(MqttCallback callback) {
        if (mqttConnectUtil == null) return;
        mqttConnectUtil.setCallback(callback);
    }

    public void setListener(MqttUtilConnectListener listener){
        if (mqttConnectUtil == null) return;
        mqttConnectUtil.setListener(listener);
    }
}
